package service

import (
	"context"
	"encoding/json"
	"k8s-dash/utils"
	appsV1 "k8s.io/api/apps/v1"
	metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type daemonset struct{}

var Daemonset daemonset

type DsResp struct {
	Total int                `json:"total"`
	Items []appsV1.DaemonSet `json:"items"`
}
type DsToNS struct {
	Namespace string `json:"namespaces"`
	DeployNum int    `json:"deploy_num"`
}

func (p *daemonset) GetDsList(filterName, namespace string, limit, page int) (resp *DsResp, err error) {
	dsList, err := utils.K8sClient.K8sClient.AppsV1().DaemonSets(namespace).List(context.TODO(), metaV1.ListOptions{})
	if err != nil {
		return nil, err
	}
	//清洗数据
	selectedData := &dataSelector{
		GenericDataList: p.toCells(dsList.Items),
		DataSelectQuery: &DataSelectorQuery{
			Filter:   &FilterQuery{filterName},
			Paginate: &PageQuery{limit, page},
		},
	}
	//先过滤
	sd := selectedData.Filter()
	total := len(sd.GenericDataList)
	//排序
	data := sd.Sort().Paginate()
	//再将数据装换为appsV1.Deployment
	ds := p.FromCells(data.GenericDataList)
	//返回数据
	return &DsResp{
		Total: total,
		Items: ds,
	}, nil
}

// GetDsDetail 获取详情
func (p *daemonset) GetDsDetail(name, namespace string) (ds *appsV1.DaemonSet, err error) {
	daemonSet, err := utils.K8sClient.K8sClient.AppsV1().DaemonSets(namespace).Get(context.TODO(), name, metaV1.GetOptions{})
	if err != nil {
		return nil, err
	}
	return daemonSet, nil
}

// DeleteDs 删除ds
func (p *daemonset) DeleteDs(name, namespace string) (err error) {
	return utils.K8sClient.K8sClient.AppsV1().DaemonSets(namespace).Delete(context.TODO(), name, metaV1.DeleteOptions{})
}

// UpdateDs 更新ds
func (p *daemonset) UpdateDs(content, namespace string) (err error) {
	var ds = &appsV1.DaemonSet{}
	if err := json.Unmarshal([]byte(content), ds); err != nil {
		return err
	}
	if _, err := utils.K8sClient.K8sClient.AppsV1().DaemonSets(namespace).Update(context.TODO(), ds, metaV1.UpdateOptions{}); err != nil {
		return err
	}
	return nil
}

// 类型转换的方法 coreV1.pod => DataCell,DataCell => coreV1.pod
func (p *daemonset) toCells(ds []appsV1.DaemonSet) []DataCell {
	cells := make([]DataCell, len(ds))
	for i := range ds {
		cells[i] = dsCell(ds[i])
	}
	return cells
}

func (p *daemonset) FromCells(cells []DataCell) []appsV1.DaemonSet {
	ds := make([]appsV1.DaemonSet, len(cells))
	for i := range cells {
		ds[i] = appsV1.DaemonSet(cells[i].(dsCell))
	}
	return ds
}
